package com.qf.ability.message.handler.base;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * author Ken
 * create_time 2022/10/16
 */
@ChannelHandler.Sharable
public abstract class BaseInChannelHandler<T> extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg.getClass() == getType() && isSupport((T) msg)) {
            //类型匹配成功
            hander(ctx, (T) msg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    protected abstract void hander(ChannelHandlerContext ctx, T msg);

    protected boolean isSupport(T msg){
        return true;
    }

    /**
     * 获取当前类的泛型类型
     * @return
     */
    protected Class getType(){
        //获取父类类型
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        //
        if (genericSuperclass instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
            //获取泛型类型
            Type[] types = parameterizedType.getActualTypeArguments();
            return (Class) types[0];
        }
        return Object.class;
    }
}
